package cn.shop.merchant.config;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

import static cn.shop.utils.constant.Constant.UID;

/**
 * @author : 李一涵
 * @date : Created in 2021-11-4 14:32
 * @description :
 */
@Component
public class AutoMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        long loginId = getLoginId();
        long uid = getUid();
        this.fillStrategy(metaObject, "createTime", LocalDateTime.now())
                .fillStrategy(metaObject, "createId", loginId)
                .fillStrategy(metaObject, "updateTime", LocalDateTime.now())
                .fillStrategy(metaObject, "updateId", loginId)
                .fillStrategy(metaObject, "uid", uid);

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        long loginId = getLoginId();
        this.fillStrategy(metaObject, "updateTime", LocalDateTime.now())
                .fillStrategy(metaObject, "updateId", loginId);
    }

    private long getLoginId() {
        long loginId = 0;
        try {
            loginId = StpUtil.getLoginIdAsLong();
        } catch (Exception ignored) {
        }
        return loginId;
    }

    private long getUid() {
        long uid = 0;
        try {
            uid = StpUtil.getSession().getLong(UID);
        } catch (Exception ignored) {}
        return uid;
    }

}
